package com.czxy.changgou4.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.czxy.changgou4.mapper.CategoryMapper;
import com.czxy.changgou4.pojo.Category;
import com.czxy.changgou4.service.CategoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 桐叔
 * @email liangtong@itcast.cn
 */
@Service
@Transactional
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Override
    public List<Category> selectAll() {
        // 1 查询所有，排序parent_id升序
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("parent_id");
        List<Category> categoryList = baseMapper.selectList(queryWrapper);
        // 2 提供2个集合
        List<Category> oneLevelList = new ArrayList<>();
        Map<Integer, Category> cacheMap = new HashMap<>();
        // 3 遍历查询结果
        for(Category category: categoryList) {
            // 3.1 通过parent_id从缓存Map中查询父对象
            Category parentCategory = cacheMap.get(category.getParentId());
            // 3.2 将一级分类添加到处理后的集合中，如果不是一级分类，将当前分类添加到从缓存中获得父分类
            if(parentCategory == null) {       //category.getParentId() == 0
                // 一级分类
                oneLevelList.add(category);
            } else {
                // 二级及其以下分类
                parentCategory.getCategoryList().add(category);
            }
            // 3.3 将每一个都添加到缓存
            cacheMap.put(category.getId(), category);
        }

        // 4 返回处理后的集合
        return oneLevelList;
    }
}
